package com.common
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	/**
	 * 美的透
	 * @author lijia
	 */	
	public class Mediator
	{
		private var _view:DisplayObject;
		
		private var listenerDic:Dictionary = new Dictionary();
		
		public function Mediator(view:DisplayObject)
		{
			_view = view;
//			_view.addEventListener(Event.REMOVED_FROM_STAGE, onRemoveFromStage);
			initListener();
		}
		
		public function initListener():void{}

		public function addEventListener(target:EventDispatcher, type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void{
			if(listenerDic[type] == null){
				listenerDic[type] = [{target:target, type:type, listener:listener}];
			}else{
				listenerDic[type].push({target:target, type:type, listener:listener});
			}
			target.addEventListener(type, listener, useCapture, priority, useWeakReference);
		}

		private function onRemoveFromStage(e:Event):void{
			_view.removeEventListener(Event.REMOVED_FROM_STAGE, onRemoveFromStage);
			onRemove();
		}

		public function onRemove():void{
			for(var type:String in listenerDic){
				var arr:Array = listenerDic[type];
				for each(var obj:Object in arr){
					var target:EventDispatcher = obj.target;
					target.removeEventListener(obj.type, obj.listener);
				}
			}
		}
	}
}